BASE = sorting
PAPER = letter
PAPER_XDVI = us
SRC = ${BASE}.tex */*.tex
BIBS = 02-biblio/*.bib
LATEX = pdflatex

all: $(BASE).pdf

#all:
$(BASE).pdf: $(SRC) $(BASE).bbl
	$(LATEX) $(BASE) | tee latex.out
	if grep -q '^LaTeX Warning: Citation.*undefined' latex.out; then \
		bibtex $(BASE); \
		touch .rebuild; \
	fi
	while [ -f .rebuild -o \
		-n "`grep '^LaTeX.*Rerun' latex.out`" ]; do \
		rm -f .rebuild; \
		$(LATEX) $(BASE) | tee latex.out; \
	done
	rm latex.out

$(BASE).dvi: $(BASE).tex $(BIBS)
	$(LATEX) $(BASE) | tee latex.out
	if grep -q '^LaTeX Warning: Citation.*undefined' latex.out; then \
		bibtex $(BASE); \
		touch .rebuild; \
	fi
	while [ -f .rebuild -o \
		-n "`grep '^LaTeX.*Rerun' latex.out`" ]; do \
		rm -f .rebuild; \
		$(LATEX) $(BASE) | tee latex.out; \
	done
	rm latex.out

bibtex:
$(BASE).bbl: $(BIBS)
	-if [ -f $(BASE).aux ]; then bibtex $(BASE); fi

$(BASE).ps: $(BASE).dvi
	dvips -t $(PAPER) $^ -o $@

$(BASE)_pdf.ps: $(BASE).dvi
	dvips -t $(PAPER) -P pdf $^ -o $@

#$(BASE).pdf: $(BASE)_pdf.ps
#	ps2pdf13 -dPDFSETTINGS=/printer $^ tmp.pdf && pdfopt tmp.pdf $@ && rm tmp.pdf

xdvi:
	if [ `xwininfo -root | grep geometry | sed 's/^ *-geometry [0-9][0-9]*x\([0-9][0-9]*\)+.*$$/\1/'` -ge 1024 ]; then \
		xdvi -geometry 1026x948 -paper $(PAPER_XDVI) $(BASE).dvi; \
        else \
                xdvi -geometry 857x711 -paper $(PAPER_XDVI) $(BASE).dvi; \
        fi &

clean:
	rm -f $(BASE).bbl $(BASE).blg $(BASE).log $(BASE).dvi \
	.rebuild $(BASE).ps $(BASE).pdf *.aux $(BASE).toc $(BASE).out
